import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {UserControllerService} from "../service";
export const getCurrentUser = createAsyncThunk('/user/current', async () => {
    const response = await UserControllerService.getCurrentUserVo();
    return response.data;
})
export const userSlice=createSlice({
    name:"user",
    initialState:{
        userInfo: JSON.parse(localStorage.getItem("token_user") ?? "{}"),
    },
    reducers:{
        currentUser:(state)=>{

            return{
                ...state,
            }
        },
        logout:(state)=>{
            return{
                ...state,
                userInfo: {},
            }
        },
        login:(state,data)=>{
            localStorage.setItem("token_user",JSON.stringify(data.payload));
            return{
                ...state,
                userInfo:data.payload,
            }

        }

    },
    extraReducers:(builder)=>{
        builder.addCase(getCurrentUser.fulfilled,(state, action)=>{
            state.userInfo=action.payload;
        })
    }
});
export const {logout,login}=userSlice.actions;
export default userSlice.reducer;
